function Promise(task) {
    this.status = 'pending'
    this.value = undefined
    this.onresolvedCallbacks = []
    this.onrejectedCallbacks = []
    // 调用resolve 如果promise是pending状态则转为成功态.并且获取成功值
    let resolve = (value) => {
        if (this.status == 'pending') {
            this.status = 'fulfilled'
            this.value = value
            this.onresolvedCallbacks.forEach(element => element(value))

        }

    }
    let reject = (reason) => {
        if (this.status == 'pending') {
            this.status = 'rejected'
            this.value = reason
            this.onrejectedCallbacks.forEach(element => element(reason))
        }
    }


    try {
        task(resolve, reject)
    }
    catch (e) {
        reject(e)
    }

}

Promise.prototype.then = function (onresolved, onrejected) {
    // 如果当前then中成功和失败的回调没有传，有默认的回调函数。会把值value或者resson传给下一个then里面的回调函数
    // value => value; let fn=value => value 返回一个函数。 
    onresolved = typeof onrejected == 'function' ? onresolved : value => value
    onrejected = typeof onrejected == 'function' ? onrejected : reason => {throw reason} //throw自带return 
    if(this.status=='fulfilled'){
        onresolved(this.value)
    }

    this.onresolvedCallbacks.push(onresolved)
    this.onrejectedCallbacks.push(onrejected)

}

console.log('-------------------------------------------------')

// let promise = mypromise((resolve, reject) => {
//     // 异步任务
//     setTimeout(function () {
//         let num = Math.random()
//         if (num < 0.5) {
//             resolve(num)
//         }
//         else {
//             reject('error')
//         }
//     }, 2000)
// })
// // 成功失败函数必须都定义一个形参。将来好接收真的数据实参。
// promise.then(function (value) {
//     console.log(value)
// }, function (err) {
//     console.log(err)
// })
modules.export = Promise